package com.recommended.util;

import com.alibaba.fastjson.JSONObject;
import com.recommended.constants.WeChatConstant;
import com.recommended.dto.Menu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WeChatMenuUtil {
    private static final Logger logger = LoggerFactory.getLogger(WeChatMenuUtil.class);
    @Autowired
    private HttpRequestUtil httpRequestUtil;

    public boolean creatMenu(Menu menu, String accessToken) {
        boolean result = false;
        String url = WeChatConstant.MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);
        //将菜单对象转换成JSON字符串
        String jsonMenu = JSONObject.toJSONString(menu);
        //发起POST请求创建菜单
        JSONObject jsonObject = httpRequestUtil.httpsRequest(url, "POST", jsonMenu);
        if (null != jsonObject) {
            String errorCode = jsonObject.getString("errcode");
            String errorMsg = jsonObject.getString("errmsg");
            if (errorCode.equals("0")) {
                result = true;
            } else {
                result = false;
                logger.error("创建菜单失败 errcode：{} errmsg：{} ", errorCode, errorMsg);
            }
        }
        return result;
    }

    public String getMenu(String accessToken) {
        String result = null;
        String requestUrl = WeChatConstant.MENU_GET_URL.replace("ACCESS_TOKEN", accessToken);
        //发起GET请求查询菜单
        JSONObject jsonObject = httpRequestUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            result = jsonObject.toString();
        }
        return result;
    }

    public boolean deleteMenu(String accessToken) {
        boolean result = false;
        String requestUrl = WeChatConstant.MENU_DELETE_URL.replace("ACCESS_TOKEN", accessToken);
        //发起GET请求删除菜单
        JSONObject jsonObject = httpRequestUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            String errorCode = jsonObject.getString("errcode");
            String errorMsg = jsonObject.getString("errmsg");
            if (errorCode.equals("0")) {
                result = true;
            } else {
                result = false;
                logger.error("创建菜单失败 errcode：{} errmsg：{} ", errorCode, errorMsg);
            }
        }
        return result;
    }
}
